package a05_双指针法;

import java.util.Arrays;


/**
 * <p>
 * a04_翻转字符串里的单词
 * </p>
 *
 * @author flyduck
 * @since 2024-07-17
 */
public class a04_翻转字符串里的单词复习2 {
    public static void main(String[] args) {

        System.out.println(reverseWords("the sky is blue"));
    }

    public static String reverseWords(String s) {
        char[] oldChars = s.toCharArray();
        //去除所有空格
        char[] newChars = removeAllSpaces(oldChars);
        //整体翻转
        reverse(newChars,0,newChars.length-1);
        //翻转每一个单词
        reverseEachWord(newChars);

        return new String(newChars);
    }

    //"  this  is  a  good  sample  "
    private static char[] removeAllSpaces(char[] oldChars) {
        int slowIdx = 0;
        int fastIdx = 0;
        while (fastIdx < oldChars.length) {
            if(oldChars[fastIdx] != ' '){
                if(slowIdx != 0){
                    oldChars[slowIdx] = ' ';
                    slowIdx++;
                }
                while (fastIdx < oldChars.length && oldChars[fastIdx] != ' ') {
                    oldChars[slowIdx] = oldChars[fastIdx];
                    slowIdx++;
                    fastIdx++;
                }
            }else {
                fastIdx++;
            }
        }
        return Arrays.copyOfRange(oldChars, 0, slowIdx);
    }



    private static void reverse(char[] chars, int leftIdx, int rightIdx) {
        while (leftIdx < rightIdx) {
            char temp = chars[leftIdx];
            chars[leftIdx] = chars[rightIdx];
            chars[rightIdx] = temp;
            leftIdx++;
            rightIdx--;
        }
    }

    private static void reverseEachWord(char[] newChars) {
        int leftIdx = 0;
        int rightIdx = 0;
        while (rightIdx < newChars.length) {
            if(rightIdx == newChars.length - 1 || newChars[rightIdx + 1] == ' '){
                reverse(newChars, leftIdx, rightIdx);
                leftIdx = rightIdx + 2;
                rightIdx = leftIdx;
            }else {
                rightIdx++;
            }
        }
    }

}
